<template>
  <view class="container">
    <!-- 积分余额展示 -->
    <view class="balance-card">
      <view class="balance-info">
        <text class="balance-label">当前积分余额</text>
        <text class="balance-value">{{ formatPoint(accountInfo.pointBalance) }}</text>
      </view>
      <text class="balance-desc">观看广告获得积分奖励</text>
    </view>

    <!-- 广告区域 -->
    <view class="ad-section">
      <text class="section-title">观看广告赚积分</text>
      
      <!-- 广告列表 -->
      <view class="ad-list">
        <view 
          class="ad-item" 
          v-for="(ad, index) in adList" 
          :key="index"
          @click="watchAd(ad)"
        >
          <view class="ad-info">
            <text class="ad-title">{{ ad.title }}</text>
            <text class="ad-reward">奖励：{{ ad.reward }}积分</text>
            <text class="ad-duration">时长：{{ ad.duration }}秒</text>
          </view>
          <view class="ad-action">
            <button class="watch-btn" :disabled="ad.watching">
              {{ ad.watching ? '观看中...' : '立即观看' }}
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 观看记录 -->
    <view class="history-section">
      <text class="section-title">观看记录</text>
      <view v-if="watchHistory.length === 0" class="no-history">
        <text class="no-history-text">暂无观看记录</text>
      </view>
      <view v-else class="history-list">
        <view 
          class="history-item" 
          v-for="(item, index) in watchHistory" 
          :key="index"
        >
          <text class="history-title">{{ item.title }}</text>
          <text class="history-reward">+{{ item.reward }}积分</text>
          <text class="history-time">{{ formatTime(item.time) }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCurrentAccount } from '@/api/user.js'

export default {
  data() {
    return {
      accountInfo: {}, // 账户信息
      adList: [
        {
          id: 1,
          title: '穿山甲广告',
          reward: 100,
          duration: 30,
          platform: 'pangolin',
          watching: false
        },
        {
          id: 2,
          title: 'Taku广告',
          reward: 150,
          duration: 45,
          platform: 'taku',
          watching: false
        }
      ],
      watchHistory: [] // 观看历史
    }
  },
  onLoad() {
    this.loadAccountInfo()
    this.loadWatchHistory()
  },
  onShow() {
    // 每次显示页面时刷新账户信息
    this.loadAccountInfo()
  },
  methods: {
    // 加载账户信息
    async loadAccountInfo() {
      try {
        const res = await getCurrentAccount()
        this.accountInfo = res.data
      } catch (error) {
        console.error('加载账户信息失败:', error)
      }
    },
    
    // 加载观看历史
    loadWatchHistory() {
      const history = uni.getStorageSync('watchHistory')
      if (history) {
        this.watchHistory = history
      }
    },
    
    // 观看广告
    async watchAd(ad) {
      if (ad.watching) return
      
      try {
        // 设置观看状态
        ad.watching = true
        
        uni.showLoading({
          title: '加载广告中...'
        })
        
        // 模拟广告加载
        await this.simulateAdLoad(ad.duration * 1000)
        
        uni.hideLoading()
        
        // 模拟广告回调
        await this.simulateAdCallback(ad)
        
        // 更新账户信息
        await this.loadAccountInfo()
        
        uni.showToast({
          title: `获得${ad.reward}积分`,
          icon: 'success'
        })
        
      } catch (error) {
        uni.hideLoading()
        console.error('观看广告失败:', error)
        uni.showToast({
          title: '观看失败',
          icon: 'none'
        })
      } finally {
        ad.watching = false
      }
    },
    
    // 模拟广告加载
    simulateAdLoad(duration) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve()
        }, duration)
      })
    },
    
    // 模拟广告回调
    async simulateAdCallback(ad) {
      // 这里应该调用实际的广告回调接口
      // POST /agg/callback/pangolin 或 /agg/callback/taku
      
      const callbackData = {
        userId: this.accountInfo.userId,
        adId: `ad_${ad.id}_${Date.now()}`,
        reward: ad.reward,
        duration: ad.duration,
        complete: true
      }
      
      // 保存观看记录
      this.saveWatchHistory({
        title: ad.title,
        reward: ad.reward,
        time: new Date().toISOString()
      })
      
      console.log('广告回调数据:', callbackData)
    },
    
    // 保存观看记录
    saveWatchHistory(record) {
      this.watchHistory.unshift(record)
      
      // 最多保存20条记录
      if (this.watchHistory.length > 20) {
        this.watchHistory = this.watchHistory.slice(0, 20)
      }
      
      // 保存到本地存储
      uni.setStorageSync('watchHistory', this.watchHistory)
    },
    
    // 格式化积分
    formatPoint(point) {
      return (point || 0).toFixed(2) + '分'
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString()
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 30rpx;
}

.balance-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
  color: #fff;
  text-align: center;
}

.balance-info {
  margin-bottom: 20rpx;
}

.balance-label {
  font-size: 28rpx;
  opacity: 0.8;
  display: block;
  margin-bottom: 10rpx;
}

.balance-value {
  font-size: 48rpx;
  font-weight: bold;
  display: block;
}

.balance-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

.ad-section, .history-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
}

.ad-list {
  margin-bottom: 30rpx;
}

.ad-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  transition: all 0.3s;
}

.ad-item:last-child {
  margin-bottom: 0;
}

.ad-item:hover {
  border-color: #667eea;
}

.ad-info {
  flex: 1;
  margin-right: 20rpx;
}

.ad-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.ad-reward {
  font-size: 26rpx;
  color: #52c41a;
  display: block;
  margin-bottom: 5rpx;
}

.ad-duration {
  font-size: 24rpx;
  color: #999;
}

.watch-btn {
  padding: 20rpx 40rpx;
  background: #667eea;
  color: #fff;
  font-size: 26rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
}

.watch-btn::after {
  border: none;
}

.watch-btn[disabled] {
  background: #ccc;
  color: #999;
}

.no-history {
  text-align: center;
  padding: 60rpx 0;
}

.no-history-text {
  font-size: 28rpx;
  color: #999;
}

.history-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.history-item:last-child {
  border-bottom: none;
}

.history-title {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  margin-right: 20rpx;
}

.history-reward {
  font-size: 26rpx;
  color: #52c41a;
  font-weight: bold;
  margin-right: 20rpx;
}

.history-time {
  font-size: 22rpx;
  color: #999;
  white-space: nowrap;
}
</style>
